<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        style="width: 190px;"
        class="filter-item"
        placeholder="请输入卡编号"
        v-model="queryForm.cardNo"
      >
      </el-input>
      <el-input
        style="width: 150px;"
        class="filter-item"
        placeholder="请输入领卡人姓名"
        v-model="queryForm.owerName"
      >
      </el-input>
      <el-input
        style="width: 150px;"
        class="filter-item"
        placeholder="请输入领卡人电话"
        v-model="queryForm.owerPhone"
      >
      </el-input>
      <el-select
        clearable
        style="width: 135px"
        class="filter-item"
        v-model="queryForm.status"
        placeholder="请选择卡状态"
      >
        <el-option
          v-for="(val, key) in typeOptions"
          :key="key"
          :label="val"
          :value="key"
        >
        </el-option>
      </el-select>
      <el-button
        class="filter-item"
        @click="doQuery"
        type="primary"
        icon="el-icon-search"
        >查询</el-button
      >
      <el-input
        style="width: 150px;"
        class="filter-item"
        placeholder="请输入卡批次"
        v-model="cardBatch"
      >
      </el-input>
      <el-button
        class="filter-item"
        @click="watch"
        type="primary"
        icon="el-icon-warning"
        >激活</el-button
      >
    </div>
    <el-table v-loading="loading" :data="records" style="width: 100%">
      <el-table-column
        prop="batchNo"
        label="卡批次号"
        width="150"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="typeClass"
        label="类型分类"
        width="150"
        align="center"
      >
        <template slot-scope="scope">
          {{ Dicts.TYPE_CLASS[scope.row.typeClass] }}
        </template>
      </el-table-column>
      <el-table-column prop="cardNo" label="卡编号" width="250" align="center">
      </el-table-column>
      <el-table-column
        prop="serialNumber"
        label="卡序列号"
        width="250"
        align="center"
      >
      </el-table-column>
      <el-table-column prop="expdate" label="有效期" width="250" align="center">
      </el-table-column>
      <el-table-column
        prop="owerName"
        label="领卡人姓名"
        width="150"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="owerPhone"
        label="领卡人电话"
        width="150"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="isReceive"
        label="是否领取"
        width="150"
        align="center"
      >
        <template slot-scope="scope">
          {{ Dicts.DOORCARD_IS_RECEIVE[scope.row.isReceive] }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="卡状态" width="150" align="center">
        <template slot-scope="scope">
          {{ Dicts.DOORCARD_STATUS[scope.row.status] }}
        </template>
      </el-table-column>
      <el-table-column
        prop="receiveTime"
        label="领取时间"
        width="250"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="activeTime"
        label="激活时间"
        width="250"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="bindingTime"
        label="绑定时间"
        width="250"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="lostTime"
        label="挂失时间"
        width="250"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="logoutTime"
        label="注销时间"
        width="250"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="modifyTime"
        label="修改时间"
        width="250"
        align="center"
      >
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        class-name="small-padding"
        fixed="right"
        width="300"
      >
        <template slot-scope="scope">
          <el-button
            v-permission="'doorCardComm:dcWrite'"
            type="primary"
            size="mini"
            v-if="scope.row.status != 3"
            @click="dcWrite(scope.row.cardNo, scope.row.rowId)"
            icon="el-icon-service"
            circle
            title="发卡"
          ></el-button>
          <el-button
            v-permission="'doorCardComm:receiveCard'"
            size="mini"
            type="success"
            v-if="scope.row.isReceive == 0"
            @click="receiveCard(scope.row.rowId)"
            title="确认领取"
            icon="el-icon-success"
            circle
          ></el-button>
          <el-button
            v-permission="'doorCardComm:bindCommunity'"
            type="warning"
            size="mini"
            v-if="scope.row.status == 1"
            @click="bindCommunity(scope.row.rowId)"
            icon="el-icon-setting"
            circle
            title="绑定小区"
          ></el-button>
          <el-button
            v-permission="'doorCardComm:out'"
            size="mini"
            type="warning"
            v-if="scope.row.status != 0 && scope.row.status != 3"
            @click="handleLogOut(scope.row.rowId)"
            title="注销"
            icon="el-icon-warning"
            circle
          ></el-button>
          <el-button
            v-permission="'doorCardComm:active'"
            size="mini"
            type="success"
            v-if="scope.row.status == 0 || scope.row.status == 3"
            @click="activationCard(scope.row.rowId)"
            title="激活"
            icon="el-icon-warning"
            circle
          ></el-button>
          <el-button
            v-permission="'doorCardComm:delete'"
            size="mini"
            type="danger"
            @click="handleDelete(scope.row.rowId)"
            title="删除"
            icon="el-icon-delete"
            circle
          ></el-button>
          <el-button
            size="mini"
            type="default"
            @click="oplog(scope.row.rowId)"
            title="操作日志"
            icon="el-icon-document"
            circle
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryForm.current"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryForm.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="queryForm.total"
      >
      </el-pagination>
    </div>

    <el-dialog
      :title="`${communityForm.doorCardId ? '选择' : '选择'}小区`"
      :visible.sync="communityFormVisible"
      width="50%"
    >
      <el-form
        :model="communityForm"
        label-width="80px"
        :rules="communityFormRules"
        ref="communityForm"
      >
        <!-- <el-form-item label="省份"  >
          <el-select v-model="communityForm.provinceId" placeholder="省份" style="width: 100%;" @change="chooseProvince">
            <el-option v-for="(item, index) in provinces" :key="index" :value="item.rowId" :label="item.cnName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市" >
          <el-select v-model="communityForm.cityId" placeholder="城市" style="width: 100%;"  @change="chooseCity">
            <el-option v-for="(item, index) in citys" :key="index" :value="item.rowId" :label="item.cnName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区县">
          <el-select v-model="communityForm.districtId" placeholder="区县" style="width: 100%;" @change="chooseDistrict">
            <el-option v-for="(item, index) in districts" :key="index" :value="item.rowId" :label="item.cnName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="小区" prop="communityId" >
          <el-select v-model="communityForm.communityId" placeholder="小区" style="width: 100%;" @change="chooseCommunity" filterable>
            <el-option v-for="(item, index) in communitys" :key="index" :value="item.rowId" :label="item.name"></el-option>
          </el-select>
        </el-form-item> -->
        <el-transfer
          filterable
          :filter-method="filterMethod"
          filter-placeholder="请输入小区"
          v-model="value2"
          :data="data2"
          :titles="['未绑定小区', '已绑定小区']"
        >
        </el-transfer>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="communityFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveCommunityDoor">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="`查看门卡操作日志详情`"
      :visible.sync="detailFormVisible"
      width="70%"
    >
      <el-table v-loading="loading" :data="detailRecords" style="width: 100%">
        <el-table-column prop="rowId" label="编号" width="100">
        </el-table-column>
        <el-table-column prop="realName" label="操作人" width="100">
        </el-table-column>
        <el-table-column prop="cardNo" label="卡号" width="200">
        </el-table-column>
        <el-table-column prop="opEvent" label="操作事件" width="100">
          <template slot-scope="scope">
            {{ Dicts.OP_EVENT[scope.row.opEvent] }}
          </template>
        </el-table-column>
        <el-table-column prop="opDesc" label="操作描述" width="150">
        </el-table-column>
        <el-table-column prop="roomName" label="区域" width="400">
        </el-table-column>
        <el-table-column prop="grantUserName" label="授权目标用户" width="150">
        </el-table-column>
        <el-table-column prop="delayBeforeDate" label="延期前日期" width="150">
        </el-table-column>
        <el-table-column prop="delayAfterDate" label="延期后日期" width="150">
        </el-table-column>
        <el-table-column> </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryDoorCardComm,
  deleteDoorCard,
  cancelDoorCard,
  addCommunityDoor,
  activationDoorCard,
  receiveCard,
  volumeActiveDoorCard,
  selectDoorCardOplog
} from '@/api/card'
import { getAllCommunity, getNoBindAllCommunity } from '@/api/area'
import { editDoorCard } from '@/api/community'
export default {
  name: 'doorCardComm',
  data() {
    return {
      detailFormVisible: false,
      detailRecords: [],
      cardBatch: '',
      data2: [],
      value2: [],
      loading: false,
      communityFormVisible: false,
      communityForm: [],
      queryForm: {
        current: 1,
        pages: 0,
        total: 0,
        size: 10,
        status: undefined,
        title: undefined
      },
      typeOptions: Dicts.DOORCARD_STATUS,
      communityFormRules: {
        // communityId: [
        //   { required: true, message: '请选择小区', trigger: 'change' }
        // ]
      },
      exampleForm: []
    }
  },
  created() {
    this.doQuery()
    this.readerd8().then(d8 => {
      this.reader = d8
    })
  },
  methods: {
    handleCurrentChange(current) {
      this.queryForm.current = current
      this.doQuery()
    },
    handleSizeChange(size) {
      this.queryForm.size = size
      this.doQuery()
    },
    doQuery() {
      this.loading = true
      queryDoorCardComm(this.queryForm).then(({ data: { data } }) => {
        this.queryForm.current = data.current
        this.queryForm.pages = data.pages
        this.queryForm.total = data.total
        this.queryForm.size = data.size
        this.records = data.records
        this.loading = false
      })
    },
    oplog(rowId) {
      this.exampleForm.doorCardId = rowId
      selectDoorCardOplog(this.exampleForm).then(
        ({ data: { code, data, msg } }) => {
          this.detailFormVisible = true
          this.detailRecords = data
          this.loading = false
        }
      )
    },
    watch() {
      this.$confirm('此操作将批量激活该批次的所有门禁卡, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        volumeActiveDoorCard(this.cardBatch).then(({ data: { data, msg } }) => {
          this.doQuery()
          this.$message({
            showClose: true,
            message: '该批次下的卡片激活成功',
            type: 'success'
          })
        })
      })
    },
    handleDelete(rowId) {
      this.$confirm('此操作将删除该门禁卡, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDoorCard(rowId).then(({ data: { data, msg } }) => {
          this.doQuery()
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
      })
    },
    bindCommunity(rowId) {
      this.communityFormVisible = true
      this.data2 = []
      this.value2 = []
      this.communityForm = {}
      // this.data2 = []
      this.communityForm.doorCardId = rowId
      const generateData2 = _ => {
        const dataOut = []
        getAllCommunity().then(({ data: { data } }) => {
          this.bind = data
          const bindCom = this.bind
          const pinyin = []
          bindCom.forEach((community, index) => {
            this.$set(pinyin, index, community.communityName)
            dataOut.push({
              label: community.communityName,
              key: community.communityId,
              pinyin: pinyin[index]
            })
          })
        })
        return dataOut
      }
      getNoBindAllCommunity(rowId).then(({ data: { data } }) => {
        // this.value2 = []
        this.noBind = data
        const NoBindCom = this.noBind
        NoBindCom.forEach((community, index) => {
          this.$set(this.value2, index, community.communityId)
          // this.value2 = [1, 2]
        })
      })
      this.data2 = generateData2()
      this.$refs.communityForm && this.$refs.communityForm.resetFields()
    },
    filterMethod(query, item) {
      return item.pinyin.indexOf(query) > -1
    },
    saveCommunityDoor() {
      this.$refs.communityForm.validate(valid => {
        if (valid) {
          this.communityForm.communityIds = this.value2
          addCommunityDoor(this.communityForm).then(
            ({ data: { data, msg, code } }) => {
              if (code === 0) {
                this.doQuery()
                this.communityFormVisible = false
              }
              this.$message({
                showClose: true,
                message: '绑定小区成功',
                type: code === 0 ? 'success' : 'error'
              })
            }
          )
        } else {
          return false
        }
      })
    },
    handleLogOut(rowId) {
      this.$confirm('此操作将注销该门禁卡, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelDoorCard(rowId).then(({ data: { data, msg } }) => {
          this.doQuery()
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
      })
    },
    activationCard(rowId) {
      this.$confirm('此操作将激活该门禁卡, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        activationDoorCard(rowId).then(({ data: { data, msg } }) => {
          this.doQuery()
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
      })
    },
    dcWrite(cardNo, rowId) {
      let ret
      let serialNumber
      // 调用控件对象dc_init方法，初始化端口
      ret = this.reader.dc_init(100, 115200)
      // 成功则返回串口标识符>0，失败返回负值，见错误代码表
      if (ret < 0) {
        alert('初始化失败！')
        return
      } else if (ret > 0) {
        // 发卡
        ret = this.reader.dc_card_double(0) // 0为单卡操作模式
        serialNumber = this.reader.get_bstrRBuffer_asc
        if (ret !== 0) {
          alert('未发现卡片！')
          this.reader.dc_beep(10)
          this.reader.dc_exit()
          return
        } else {
          // 密钥加载及认证
          this.reader.put_bstrSBuffer_asc = 'FDB0916AC12FFF07806977681FE2ABC9'
          this.reader.dc_load_key(0, 13)
          ret = this.reader.dc_authentication(0, 13)
          if (ret !== 0) {
            alert('认证失败')
            this.reader.put_bstrSBuffer_asc = 'FFFFFFFFFFFFFF078069FFFFFFFFFFFF' // 还原设备认证key
            this.reader.dc_load_key(0, 13)
            this.reader.dc_beep(10)
            this.reader.dc_exit()
            return
          } else {
            this.reader.put_bstrSBuffer_asc = cardNo + '000000000000'
            ret = this.reader.dc_write(52)
            if (ret !== 0) {
              this.reader.dc_beep(10)
              this.reader.put_bstrSBuffer_asc =
                'FFFFFFFFFFFFFF078069FFFFFFFFFFFF' // 还原设备认证key
              this.reader.dc_load_key(0, 13)
              this.reader.dc_exit()
              alert('写入失败！')
              return
            } else {
              this.reader.put_bstrSBuffer_asc =
                'FFFFFFFFFFFFFF078069FFFFFFFFFFFF' // 还原设备认证key
              this.reader.dc_load_key(0, 13)
              this.reader.dc_beep(100)
              this.reader.dc_exit()
              editDoorCard(rowId, serialNumber).then(
                ({ data: { data, msg } }) => {
                  this.$message({
                    showClose: true,
                    message: '发卡成功！',
                    type: 'success'
                  })
                }
              )
            }
          }
        }
      }
    },
    receiveCard(rowId) {
      this.$confirm('是否确认已领取该门禁卡?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        receiveCard(rowId).then(({ data: { data, msg } }) => {
          this.doQuery()
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
      })
    }
  },
  components: {}
}
</script>

<style scoped></style>
<style>
.el-transfer-panel {
  width: 40% !important;
}
</style>
